﻿using System;
using System.Collections.Generic;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Win32;

namespace MappingGeneratorProKeygen
{
    class Program
    {
        private static readonly Regex LicenseKeyPattern = new Regex("[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}");
        static void Main(string[] args)
        {
            //var version = LicenseManager.GetProductVersion();
            var vsVersion = LicenseManager.GetVsCurrentVersion();

            // Console.WriteLine($"请输入MappingGeneratorPro版本号，默认版本={version}");
            // var input = Console.ReadLine();
            // if (!string.IsNullOrEmpty(input)) version = input;

            Console.WriteLine($"请输入Vs版本号，默认版本={vsVersion}，可选值：Vs2017、Vs2019、Vs2022");
            var input = Console.ReadLine();
            if (!string.IsNullOrEmpty(input)) vsVersion = input;

            string name = WindowsIdentity.GetCurrent().Name;
            var (licenseEmail, licenseKey) = GenerateRandomLicensePair();

            LicenseManager.UseVsVersion(vsVersion);
            var license = new LicenseManager.License
            {
                ActivatedOn = DateTime.Now.ToString("yyyy-MM-dd"),
                HashedLicenseKey = LicenseManager.CalculateHash(licenseKey),
                RegisteredProductVersion = "Unlimited",
                ProductName = "MappingGeneratorPro"
            };
            license.ThumbPrint = CalculateThumbPrint(license, name, vsVersion);
            TrySaveLicenseInfo(license, vsVersion);

            var valid = license.IsValid();

            Console.WriteLine($"License信息已写入(验证={valid})，重启VS后生效");

            Console.ReadKey();
        }

        internal static string CalculateThumbPrint(LicenseManager.License license, string name, string vsVersion)
        {
            return LicenseManager.CalculateHash(license.ActivatedOn + "||" + license.HashedLicenseKey + "||" + license.RegisteredProductVersion + "||" + name + "||" + vsVersion);
        }


        internal static bool TrySaveLicenseInfo(LicenseManager.License license, string vsVersion)
        {
            var registryKey = LicenseManager.AccessRegistryKeyForEdit(Registry.CurrentUser, "Software", "MappingGenerator", vsVersion);
            if (registryKey != null)
            {
                registryKey.SetValue("Product", license.ProductName, RegistryValueKind.String);
                registryKey.SetValue("LicenseKey", license.HashedLicenseKey, RegistryValueKind.String);
                registryKey.SetValue("ActivatedOn", license.ActivatedOn, RegistryValueKind.String);
                registryKey.SetValue("RegisteredProductVersion", license.RegisteredProductVersion, RegistryValueKind.String);
                registryKey.SetValue("ThumbPrint", license.CalculateThumbPrint(), RegistryValueKind.String);
                return true;
            }
            return false;
        }

        private static (string licenseEmail, string licenseKey) GenerateRandomLicensePair()
        {
            var random = new Random(Environment.TickCount);
            var chars = new List<char>();
            for (char i = 'a'; i <= 'z'; i++)
            {
                chars.Add(i);
            }
            for (char i = 'A'; i <= 'Z'; i++)
            {
                chars.Add(i);
            }

            var key = new List<string>();
            for (var i = 0; i < 4; i++)
            {
                var group = new char[5];
                for (var j = 0; j < group.Length; j++)
                {
                    var index = random.Next(0, chars.Count);
                    group[j] = chars[index];
                }

                key.Add(new string(group).ToUpper());
            }

            return ("pedoc@qq.com", string.Join("-", key));
        }


        //MappingGeneratorPro.LicenseDialogViewModel
        private bool ActivationDataCorrect(string licenseEmail, string licenseKey)
        {
            if (string.IsNullOrWhiteSpace(licenseEmail))
            {
                return false;
            }
            if (!licenseEmail.Contains("@"))
            {
                return false;
            }
            if (!LicenseKeyPattern.IsMatch(licenseKey))
            {
                return false;
            }
            return true;
        }
    }
}
